using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using MvcDome01.Db;
using MvcDome01.Models;
using MvcDome01.ResultModel;

namespace MvcDome01.Controllers
{
    public class StudentController : Controller
    {
        private readonly MvcDomeDb _db;

        public StudentController()
        {
            _db = new MvcDomeDb();
            var school = _db.School.Where(x => x.IsDel == false).FirstOrDefault();
            if (school == null)
            {
                var schools = new List<School>
                {
                    new School{
                        SchoolName="1中"
                    },
                    new School{
                        SchoolName="2中"
                    },
                    new School{
                        SchoolName="3中"
                    }
                };
                _db.School.AddRange(schools);
                _db.SaveChanges();
            }
        }
            public IActionResult Index()
            {
                var student = _db.Student.Where(x=>x.IsDel==false).ToArray();
                return View(student);
            }
            public IActionResult CreateOrEdit(int id)
            {
                var student = _db.Student.Where(x=>x.Id==id && x.IsDel==false).FirstOrDefault();
                return View(student);
            }
            public IActionResult Delete(int id)
            {
                var student = _db.Student.Where(x=>x.Id==id && x.IsDel==false).FirstOrDefault();
                student.IsDel=true;
                student.Update=DateTime.Now;
                _db.Student.Update(student);
                _db.SaveChanges();
                return RedirectToAction("Index");
            }
            public IActionResult Save(Student student)
            {
                if(student==null ||student.Id==0)
                {
                    _db.Student.Add(student);
                    _db.SaveChanges();
                }else{
                    student.Update=DateTime.Now;
                    _db.Student.Update(student);
                    _db.SaveChanges();
                }
                return Ok();
            }
            public IActionResult Query(KeyWord resulword)
            {
                List<Student> students;
                var db = new MvcDomeDb();
                if(resulword.word==null || resulword.word.Length<=0)
                {
                    students = db.Student.Where(x=>x.IsDel==false).ToList();
                }else{
                    students = db.Student.Where(x => x.IsDel == false && x.StuName.Contains(resulword.word)).ToList();
                }
                return Json(students);
            }
        }
    }